package com.issc.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionUtil {
    private static final Logger log= LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 创建实例
     *
     * */
    public static Object newInstance(Class<?> clz){
        Object instance;
        try {
            instance=clz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            log.error("create new instance failure",e);
            throw  new RuntimeException("create new instance failure",e);
        }
        return instance;
    }

    /**
     * 调用方法
     * @param obj 对象的实例
     * @param method 方法
     * @param arg 参数
     * @return
     */
    public static Object invokeMethod(Object obj, Method method,Object...arg){
        Object result = null;

        try {
            method.setAccessible(true);
            result=method.invoke(obj,arg);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *
     * @param object
     * @param field
     * @param value
     * @return
     */
    public  static  Object getField(Object object, Field field,Object value){
        field.setAccessible(true);
        try {
            field.set(object,value);
        } catch (IllegalAccessException e) {
            log.error("set field failure",e);
            throw new RuntimeException(e);
        }
        return field;
    }
}
